export default class WebSocketClient {
    private client: any;
    private interval: any;
    private listeners: any = {};

    constructor() {
        this.connectServer();
    }

    public connectServer() {
        this.listeners = {};
        if (this.interval) clearInterval(this.interval);
        this.client = new WebSocket('wss://www.noodlebox.ie/ws?token=08f088416bba7ca2ff8754aac9bf666303fbcbb5e00d31e2109f599c9aa34b68');
        this.client.onopen = () => {
            console.log('WebSocket connected');
            setInterval(() => {
                this.send('heartbeat', {
                    time: Date.now(),
                });
            }, 2000);
        };

        this.client.onmessage = (message: any) => {
            //console.log('Received message:', message.data);
            const data = JSON.parse(message.data);
            if (!data.event || data.event === 'heartbeat') {
                return;
            }

            Object.keys(this.listeners).forEach((key) => {
                if (key === data.event) {
                    this.listeners[key](data);
                }
            });
        };

        this.client.onclose = () => {
            console.log('WebSocket disconnected');
            clearInterval(this.interval);
        };

        this.client.onerror = (error: any) => {
            console.log('WebSocket error:', error);
        };
    }

    public send(event: string, data: any) {
        if (this.client.readyState === WebSocket.OPEN) {
            this.client.send(JSON.stringify({
                event,
                data,
            }));
        } else if (this.client.readyState === WebSocket.CONNECTING) {
            console.log('WebSocket is connecting...');
        } else if (this.client.readyState === WebSocket.CLOSED) {
            this.destroy();
            this.connectServer();
        }
    }

    public listen(eventName: string, callback: any) {
        this.listeners[eventName] = callback;
        return this;
    }

    public destroy() {
        this.client.close();
        this.listeners = {};
        clearInterval(this.interval);
    }
}
